package com.dcsec.server.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.dcsec.server.bean.PrintParam;
import com.dcsec.server.bean.Result;
import com.dcsec.server.printer.ZplPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.servlet.*;
import javax.servlet.http.*;


public class PrinterController extends HttpServlet {

    private static final Logger log = LoggerFactory.getLogger(PrinterController.class);

    @Override
    public void init(ServletConfig arg0) throws ServletException {
        System.out.println("servlet初始化");

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request, response);
	}

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        try {

            PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
            if (services != null && services.length > 0) {
                for (PrintService service : services) {
                    log.error(service.getName());
                }
            }

            String printerName = request.getParameter("printerName");
            String dataJSON = request.getParameter("dataJSON");

            List<PrintParam> printParams = JSONUtil.toList(dataJSON, PrintParam.class);

            ZplPrinter.printToParams(printerName,printParams);
            doResponse(response, Result.createSuccessResult());
        } catch (Exception e) {
            log.error(e.getMessage());
            doResponse(response,Result.createErrorResult(e.getMessage()));
        }
    }

    /**
     * ajax输出数据
     * @param response
     * @param result
     * @throws IOException
     */
    protected void doResponse(HttpServletResponse response,Result result) throws IOException {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(JSONUtil.toJsonStr(result));
        response.getWriter().flush();
    }
}
